package com.juzhencms.apps.busi.web;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.busi.service.UploadService;
import com.juzhencms.apps.base.busi.service.UploadService.UploadFileParam;
import com.juzhencms.apps.base.busi.service.UploadService.UploadImgParam;
import com.juzhencms.apps.base.busi.service.UploadService.UploadResult;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.util.AliyunOSSUtil;
import com.juzhencms.apps.base.common.util.FileUtil;
import com.juzhencms.apps.base.common.util.ImageUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
@RequestMapping("/upload")
public class UploadController extends BaseController {
	
	
	@Autowired
	private UploadService uploadService;
	
	
	/**
	 * 直接返回对象，自动转换为json
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/uploadFile",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){
		
		UploadResult result=uploadService.uploadFile(file);
		return this.uploadResult(result, request);

	}
	
	
	
	/**
	 * 直接返回对象，自动转换为json
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/uploadImg",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String uploadImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){
		
		UploadImgParam uploadImgParam=uploadService.new UploadImgParam();
		//判断是否需要生成缩略图
		if(request.getParameter("imgWidth")!=null && request.getParameter("imgHeight")!=null){
			uploadImgParam.setImgWidth(new Integer(request.getParameter("imgWidth")));
			uploadImgParam.setImgHeight(new Integer(request.getParameter("imgHeight")));
			if(request.getParameter("cutType")!=null) {
				uploadImgParam.setImgCutType(request.getParameter("cutType").toString());
			}	
		}
		UploadResult result=uploadService.uploadImg(file,uploadImgParam);
		
		return this.uploadResult(result, request);
		
	}
	
	

	
	
	
	/**
	 * 直接返回对象，自动转换为json，针对编辑器4.5以上版本，当前使用编辑器4.13
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/ckeditor",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String ckeditor(@RequestParam(value = "upload", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){
		
		//提示
		Map<String,Object> msgMap = new HashMap<>();
		
		String type=request.getParameter("type");
		if(type==null || type.equals("")){
			Map data=new HashMap();
			data.put("uploaded", 0);
			msgMap.put("message","上传类型为空");
			data.put("error",msgMap);
			return WebUtil.resultString(data,request);
		}
		
		Map allowType=new HashMap();
		allowType.put("file", new String[]{"doc","docx","xls","xlsx","pdf","zip","rar","txt","jpeg","jpg","bmp","gif","png"});
		allowType.put("img", new String[]{"jpeg","jpg","bmp","gif","png"});
		allowType.put("flash", new String[]{"flv","swf"});
		
		Map allowTypeSize=new HashMap();
		allowTypeSize.put("file", 20);
		allowTypeSize.put("img", 5);
		allowTypeSize.put("flash", 5);
		
		String extName=FileUtil.getExtName(file.getOriginalFilename());
		
		String[] typeArr=(String[])allowType.get(type);
		if(typeArr==null){
			Map data=new HashMap();
			data.put("uploaded", 0);
			msgMap.put("message","错误的类型参数");
			data.put("error",msgMap);
			return WebUtil.resultString(data,request);			
		}
		
		/*if(!Arrays.asList(typeArr).contains(extName)){
			Map data=new HashMap();
			data.put("uploaded", 0);
			msgMap.put("message","错误的上传类型");
			data.put("error",msgMap);
			return WebUtil.resultString(data,request);			
		}
		
		int sizeLimit=(int)allowTypeSize.get(type);
		
		
		if(file.getSize()>sizeLimit*1024*1024){			
			Map data=new HashMap();
			data.put("uploaded", 0);
			msgMap.put("message","文件太大，请选择"+sizeLimit+"MB以内的文件");
			data.put("error",msgMap);
			return WebUtil.resultString(data,request);
		}*/
		
		
		UploadFileParam uploadFileParam=uploadService.new UploadFileParam();
		uploadFileParam.setAllowType(typeArr);
		uploadFileParam.setAllowFileSize((int)allowTypeSize.get(type));
		UploadResult uploadResult=uploadService.uploadFile(file, uploadFileParam);
		
		Map data=new HashMap();
		if(uploadResult.getResult()==1) {
			data.put("uploaded", 1);
			data.put("fileName", (new File(uploadResult.getSavePath())).getName());
			data.put("url",uploadResult.getUrlPath());
		}else {
			data.put("uploaded", 0);
			msgMap.put("message",uploadResult.getMsg());
			data.put("error",msgMap);
		}
		return WebUtil.resultString(data,request);
	}
	
	
	/**
	 * 直接返回对象，自动转换为json 支持编辑器版本4.5以下 
	 * @param name
	 * @return
	 */
	/*@RequestMapping(value="/oldckeditor",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String oldckeditor(@RequestParam(value = "upload", required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){

		String CKEditorFuncNum=request.getParameter("CKEditorFuncNum");
		if(CKEditorFuncNum==null || CKEditorFuncNum.equals("")){
			Map data=new HashMap();
			data.put("funName", 1);
			data.put("fileUrl","");
			data.put("message","错误的功能调用请求");
			return WebUtil.resultString(data,request);
		}

		String type=request.getParameter("type");
		if(type==null || type.equals("")){
			Map data=new HashMap();
			data.put("funName", 1);
			data.put("fileUrl","");
			data.put("message","上传类型为空");
			return WebUtil.resultString(data,request);
		}
		
		Map allowType=new HashMap();
		allowType.put("file", new String[]{"doc","docx","xls","xlsx","pdf","zip","rar","txt","jpeg","jpg","bmp","gif","png"});
		allowType.put("img", new String[]{"jpeg","jpg","bmp","gif","png"});
		allowType.put("flash", new String[]{"flv","swf"});
		
		Map allowTypeSize=new HashMap();
		allowTypeSize.put("file", 10);
		allowTypeSize.put("img", 1);
		allowTypeSize.put("flash", 1);
		
		String extName=FileUtil.getExtName(file.getOriginalFilename());
		
		String[] typeArr=(String[])allowType.get(type);
		if(typeArr==null){
			Map data=new HashMap();
			data.put("funName", 1);
			data.put("fileUrl","");
			data.put("message","错误的类型参数");
			return WebUtil.resultString(data,request);
		}
		
		if(!Arrays.asList(typeArr).contains(extName)){
			Map data=new HashMap();
			data.put("funName", 1);
			data.put("fileUrl","");
			data.put("message","错误的上传类型");
			return WebUtil.resultString(data,request);
		}
		
		int sizeLimit=(int)allowTypeSize.get(type);
		
		
		if(file.getSize()>sizeLimit*1024*1024){			
			Map data=new HashMap();
			data.put("funName", 1);
			data.put("fileUrl","");
			data.put("message","文件太大，请选择"+sizeLimit+"MB以内的文件");
			return WebUtil.resultString(data,request);
		}
		
		//使用时间戳生成文件名
		Date datenow=new Date();
		long thisTime=datenow.getTime();
		String fileName = thisTime+"."+extName;
		
		//使用日期生成目录
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd");
		String strDate = formatter.format(datenow);
		String uploadFilePath=this.getCommonService().getConfig().getUploadFilePath()+"/"+strDate;
		File targetFile = new File(uploadFilePath,fileName); 
		if(!targetFile.getParentFile().exists()){  
			targetFile.getParentFile().mkdirs(); 
		}

		//保存
		try {
			file.transferTo(targetFile);
		}catch (Exception e) {
			log.error("",e);
		}
		
		String fileUrl= this.getCommonService().getConfig().getUploadUrlPath()+"/"+strDate+"/"+fileName;
		
		String useOSS=this.getCommonService().getConfig().getValue("oss.endpoint");
		if(useOSS!=null && !useOSS.equals("")) {
			aliyunOSSUtil.upload(uploadFilePath+"/"+fileName);
		}
		
		Map data=new HashMap();
		data.put("funName",CKEditorFuncNum);
		data.put("fileUrl",fileUrl);
		data.put("message","上传成功");
		return WebUtil.resultString(data,request);
		
		  
	}*/
	
	private String uploadResult(UploadResult result,HttpServletRequest request){
		String jsonResult = JSON.toJSONString(result);
		
		if(request.getParameter("callback")!=null && !request.getParameter("callback").equals("")){

			//不跨域，直接输出js
			return "<script>window.parent.window."+WebUtil.getCallbackFunName(request.getParameter("callback"))+"('"+jsonResult+"');</script>";
		}else{
			return jsonResult;
		}
	}
	

}
